﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;
using VPLink2013.Framework;
using VPLink2013.Framework.Constants;
using VPLink2013.Framework.Extensions;

namespace VPLink2013.Webparts
{
    public class HandicapFondation : WebpartVPLink
    {

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Nombre d'éléments à afficher"), Category("Paramètres personnalisés")]
        public string nbItems { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Theme à afficher"), Category("Paramètres personnalisés")]
        public string theme { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Page de détails"), Category("Paramètres personnalisés")]
        public string detailsPage { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Url de la liste"), Category("Paramètres personnalisés")]
        public string listUrl { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Filtre"), Category("Paramètres personnalisés")]
        public string filtre { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("Activer la pagination"), Category("Paramètres personnalisés")]
        public bool pagination { get; set; }

        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true),
        WebDisplayName("XSl d'affichage"), Category("Paramètres personnalisés")]
        public string strXslFilePath { get; set; }

        private const string newsvpListUrl = "/NewsVP";

        #region Transformation
        private string getXslTransformation()
        {
            string strTransformation = string.Empty;
            string strXslt = string.Empty;
            if (!string.IsNullOrEmpty(strXslFilePath))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                strXslt = web.GetFileAsString(strXslFilePath);
                                string strXml = FileSerialization.CreateXmlStringFromObj(global);

                                if (!string.IsNullOrEmpty(strXslt) && !string.IsNullOrEmpty(strXml))
                                {
                                    strTransformation = GetTransformFromStyleLibrary(strXml, strXslt);
                                }
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    ContextTrace.AddTrace(string.Format("Exception lors de la transformation XSL"));
                    ContextTrace.AddTrace(string.Format("Exception {0}", ex.StackTrace));
                }
            }
            return strTransformation;
        }
        #endregion

        private Annonce mapToAnnonce(SPListItem item, bool fromNewsVP)
        {
            Annonce annonce = new Annonce();
            annonce.ID = item.ID.ToString();
            annonce.Titre = item.GetItemListFieldValueAsText(Fields.TitleField);
            annonce.TitrePiwik = annonce.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
            annonce.Surtitre = item.GetItemListFieldValueAsText(Fields.SmallTitleField);
            annonce.Chapeau = item.GetItemListFieldValueAsHtml(Fields.ChapeauNewsField);
            annonce.Body = item.GetItemListFieldValueAsHtml(Fields.BodyNewsField);
            if (fromNewsVP)
            {
                annonce.LinkDetail = string.Format("{0}/Pages/AnnonceDetail2013.aspx?ItemID={1}", item.Web.Url, annonce.ID);
            }
            else
            {
                annonce.LinkDetail = string.Format("{0}/Pages/{1}?ItemID={2}", item.Web.Url, detailsPage, annonce.ID);
            }
            if (!string.IsNullOrEmpty(VPLink2013SPHelper.GetValueDate(item, "Date publication")))
            {
                annonce.DatePublication = VPLink2013SPHelper.GetValueDate(item, "Date publication");
            }
            else
            {
                annonce.DatePublication = VPLink2013SPHelper.GetValueDate(item, "Created");
            }

            if (!string.IsNullOrEmpty(VPLink2013SPHelper.GetValuePhoto(item, "Photo3")))
                annonce.Photo1 = VPLink2013SPHelper.GetValuePhoto(item, "Photo3");
            else
                annonce.Photo1 = VPLink2013SPHelper.GetValuePhoto(item, "Photo");

            return annonce;
        }

        #region Get Items from lists
        private void getItemsFromNewsVPList(string theme)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList newsVpList = web.GetList(newsvpListUrl);
                    if (newsVpList != null)
                    {
                        SPFieldChoice themeFieldChoice = newsVpList.Fields["Theme"] as SPFieldChoice;
                        SPFieldChoice onLineFieldChoice = newsVpList.Fields["En ligne"] as SPFieldChoice;
                        SPFieldDateTime publicationField = newsVpList.Fields["Date publication"] as SPFieldDateTime;

                        StringBuilder queryBuilder = new StringBuilder();
                        queryBuilder.AppendFormat("<FieldRef Name='Title' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Created' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Theme' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Surtitre' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Chapeau' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Body' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Photo' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Photo1' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Photo3' />");
                        queryBuilder.AppendFormat("<FieldRef Name='{0}' />", onLineFieldChoice.InternalName);
                        queryBuilder.AppendFormat("<FieldRef Name='{0}' />", publicationField.InternalName);
                        SPQuery queryFields = new SPQuery()
                        {
                            ViewFields = queryBuilder.ToString()
                        };
                        SPListItemCollection items = newsVpList.GetItems(queryFields);

                        var selectedItems = items.Cast<SPListItem>()
                                                 .Where(i => themeFieldChoice.GetFieldValueAsText(i[themeFieldChoice.InternalName]).Equals(theme)
                                                 && onLineFieldChoice.GetFieldValueAsText(i[onLineFieldChoice.InternalName]).Equals("Oui"));

                        foreach (SPListItem i in selectedItems)
                        {
                            global.ListeAnnonces.Add(mapToAnnonce(i, true));
                        }
                    }
                }
            }
        }

        private void getItemsFromHandiActusList()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList handiActusList = web.GetList(listUrl);
                    if (handiActusList != null)
                    {
                        StringBuilder queryBuilder = new StringBuilder();
                        queryBuilder.AppendFormat("<FieldRef Name='Title' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Created' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Theme' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Surtitre' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Chapeau' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Body' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Photo' />");
                        queryBuilder.AppendFormat("<FieldRef Name='Photo1' />");

                        if (!string.IsNullOrEmpty(filtre))
                        {
                            SPFieldChoice filtrefieldChoice = handiActusList.Fields[filtre] as SPFieldChoice;
                            queryBuilder.AppendFormat("<FieldRef Name='{0}' />", filtrefieldChoice.InternalName);
                            SPQuery queryFields = new SPQuery()
                            {
                                ViewFields = queryBuilder.ToString()
                            };
                            SPListItemCollection listItems = handiActusList.GetItems(queryFields);
                            var selectedListItems = listItems.Cast<SPListItem>().Where(i => filtrefieldChoice.GetFieldValueAsText(i[filtrefieldChoice.InternalName]).Equals("Oui"));
                            foreach (SPListItem i in selectedListItems)
                            {
                                global.ListeAnnonces.Add(mapToAnnonce(i, false));
                            }
                        }
                        else
                        {
                            SPQuery queryFields = new SPQuery()
                            {
                                ViewFields = queryBuilder.ToString()
                            };
                            SPListItemCollection listItems = handiActusList.GetItems(queryFields);
                            foreach (SPListItem i in listItems)
                            {
                                global.ListeAnnonces.Add(mapToAnnonce(i, false));
                            }
                        }
                    }
                }
            }
        }
        #endregion

        private void buildCrtPage(StringBuilder sbNavigationPages)
        {
            string themeName = theme.Replace(" ", "_");
            sbNavigationPages.AppendLine(@"<div>");
            sbNavigationPages.AppendLine(string.Format(@"<input type='hidden' name='pageCrt_{0}' />", themeName));
            sbNavigationPages.AppendLine(@"</div>");
        }
        private void buildNextButton(StringBuilder sbNavigationPages, string nextPage)
        {
            sbNavigationPages.AppendLine(@"<div>");
            sbNavigationPages.AppendLine(string.Format(@"<input type='hidden' class='navTheme' value = '{0}' />", theme));
            sbNavigationPages.AppendLine(string.Format(@"<input type='hidden' class='navPage' value = '{0}' />", nextPage));
            sbNavigationPages.AppendLine(@"<a class=""aNavigation"">");
            sbNavigationPages.AppendLine("Page suivante   ");
            sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_right.jpg\" width=\"6\" height=\"11\">");
            sbNavigationPages.AppendLine("</a>");
            sbNavigationPages.AppendLine(@"</div>");
        }

        private void buildPreviousButton(StringBuilder sbNavigationPages, string prevPage)
        {
            sbNavigationPages.AppendLine(@"<div>");
            sbNavigationPages.AppendLine(string.Format(@"<input type='hidden' class='navTheme' value = '{0}' />", theme));
            sbNavigationPages.AppendLine(string.Format(@"<input type='hidden' class='navPage' value = '{0}' />", prevPage));
            sbNavigationPages.AppendLine(@"<a class=""aNavigation"">");
            sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_left.jpg\" width=\"6\" height=\"11\">");
            sbNavigationPages.AppendLine("   Page précédente");
            sbNavigationPages.AppendLine("</a>");
            sbNavigationPages.AppendLine(@"</div>");
        }

        protected override string GetHtml()
        {
            global = new GlobalVPLink2013();
            global.ListeAnnonces = new List<Annonce>();
            global.Filtre = new Filtre();

            try
            {
                if (!string.IsNullOrEmpty(theme))
                {
                    getItemsFromNewsVPList(theme);
                }
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace(string.Format("Exception lors de la recherche des Items NewsVP"));
                ContextTrace.AddTrace(string.Format("Exception {0}", ex.StackTrace));
            }
            try
            {
                if (!string.IsNullOrEmpty(listUrl))
                {
                    getItemsFromHandiActusList();
                }
            }
            catch (Exception ex)
            {
                ContextTrace.AddTrace(string.Format("Exception lors de la recherche des Items de la liste additionnelle"));
                ContextTrace.AddTrace(string.Format("Exception {0}", ex.StackTrace));
            }
            global.ListeAnnonces = global.ListeAnnonces.OrderByDescending(x => Convert.ToDateTime(x.DatePublication)).ToList();
            int nbPages = 1;
            if (!string.IsNullOrEmpty(nbItems))
            {
                nbPages = global.ListeAnnonces.Count() / Int32.Parse(nbItems);
                nbPages = (global.ListeAnnonces.Count() % Int32.Parse(nbItems) > 0) ? nbPages + 1 : nbPages;
            }
            string themeName = theme.Replace(" ", "_");
            string currentPage = ParamFrm(string.Format("pageCrt_{0}", themeName));
            //string themePrm = ParamFrm( "Theme" );
            if (!string.IsNullOrEmpty(currentPage))
            {
                StringBuilder sbNavigationPages = new StringBuilder();
                sbNavigationPages.AppendLine("<div class=\"pages_news\">");
                if (Int32.Parse(currentPage) == 1)
                {
                    // First page, Display only next button
                    buildNextButton(sbNavigationPages, "2");
                }
                else
                {
                    if (Int32.Parse(currentPage) == nbPages)
                    {
                        // Last page, Display only previous button
                        buildPreviousButton(sbNavigationPages, (Int32.Parse(currentPage) - 1).ToString());
                    }
                    else
                    {
                        // Display both next and previous button
                        buildPreviousButton(sbNavigationPages, (Int32.Parse(currentPage) - 1).ToString());
                        sbNavigationPages.AppendLine("<span>|</span>");
                        buildNextButton(sbNavigationPages, (Int32.Parse(currentPage) + 1).ToString());
                    }
                }
                sbNavigationPages.AppendLine("</div>");
                global.ListeAnnonces = global.ListeAnnonces.Skip((Int32.Parse(currentPage) - 1) * Int32.Parse(nbItems))
                                                            .Take(Int32.Parse(nbItems)).ToList();

                StringBuilder sbParam = new StringBuilder();
                buildCrtPage(sbParam);

                global.Filtre.NavigationPages = sbParam.ToString() + sbNavigationPages.ToString();
                ContextTrace.AddTrace(string.Format("Navigation up : {0}", global.Filtre.NavigationPages));
                global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString();
            }
            else
            {
                if (pagination == false)
                {
                    if (!string.IsNullOrEmpty(nbItems))
                    {
                        global.ListeAnnonces = global.ListeAnnonces
                                                .Take(Int32.Parse(nbItems)).ToList();
                    }
                }
                else
                {
                    if (Int32.Parse(nbItems) >= global.ListeAnnonces.Count())
                    {
                        global.ListeAnnonces = global.ListeAnnonces
                                                .Take(Int32.Parse(nbItems)).ToList();
                    }
                    else
                    {
                        // First page 
                        StringBuilder sbNavigationPages = new StringBuilder();
                        StringBuilder sbParam = new StringBuilder();
                        buildCrtPage(sbParam);
                        sbNavigationPages.AppendLine("<div class=\"pages_news\">");
                        buildNextButton(sbNavigationPages, "2");
                        sbNavigationPages.AppendLine("</div>");
                        global.Filtre = new Filtre();
                        global.ListeAnnonces = global.ListeAnnonces.Take(Int32.Parse(nbItems)).ToList();
                        global.Filtre.NavigationPages = sbParam.ToString() + sbNavigationPages.ToString();
                        global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString();
                    }
                }
            }
            string strHtml = getXslTransformation();
            ContextTrace.PrefixFileName = this.Title;
            return strHtml;
        }
    }
}
